package com.adaydayup.week_1017;

public class TotalFruit_904 {
    /*
    1  2  3  2  2
    i
    j
     */
    public static void main(String[] args) {
        int[] arr = {1, 1, 2, 3, 3, 2, 2};
//        System.out.println(totalFruit(arr));
//        System.out.println(totalFruit2(arr));
        System.out.println(total3(arr));
    }

    public static int total3(int[] fruits) {
        int len = fruits.length;
        int ans=0;
        int[] temp=new int[len+5];
        for (int i = 0, j = 0,total=0; i < len; i++) {
            if (++temp[fruits[i]]==1) total++;
            while (total>2){
                if (--temp[fruits[j++]]==0)
                total--;
            }
            ans=Math.max(ans,i-j+1);
        }
        return ans;
    }

    public static int totalFruit(int[] fruits) {
        int len = fruits.length;
        int i = 0;
        int sum = 1;
        int type1 = -1;
        int type2 = -1;
        int res = 0;
        if (len == 1) return 1;
        for (int j = 1; j < len; j++) {
            type1 = fruits[i];
            int k = i;
            if ((fruits[j] != type1) && (type2 == -1)) {
                for (; k <= j; k++) {
                    if (fruits[k] != fruits[i]) {
                        type2 = fruits[k];
                        break;
                    }
                }
            }
            if ((fruits[j] == type1) || (fruits[j] == type2)) {
                sum++;
                if (sum > res) {
                    res = sum;
                }
            } else {
                sum = sum - (k - i);
                i = k;
                j--;
                type2 = -1;
            }
        }
        return res;
    }

    public static int totalFruit2(int[] fruits) {
        int n = fruits.length, ans = 0;
        int[] cnts = new int[n + 10];
        for (int i = 0, j = 0, tot = 0; i < n; i++) {
            if (++cnts[fruits[i]] == 1) tot++;
            while (tot > 2) {
                if (--cnts[fruits[j++]] == 0) tot--;
            }
            ans = Math.max(ans, i - j + 1);
        }
        return ans;
    }

    public static int total(int[] fs) {
        int ans = 0;
        int n = fs.length;
        int[] cnts = new int[n + 10];
        for (int i = 0, j = 0, tot = 0; i < n; i++) {
            if (++cnts[fs[i]] == 1) tot++;
            while (tot > 2) {
                if (--cnts[fs[j++]] == 0) tot--;
            }
            ans = Math.max(ans, i - j + 1);
        }
        return ans;
    }
}
